#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "../inc/admin.h"
#include "../inc/data.h"
#include "../inc/flight_node.h"
#include "../inc/general.h"
#include "../inc/login.h"
#include "../inc/myInfo.h"
#include "../inc/my_flight_node.h"
#include "../inc/user_node.h"
#include "../inc/user.h"

void show_allFlight(flight_Node_p headNode)
{
    const int pageSize = 5; // 每页显示5条记录
    int currPage = 1;
    flight_Node_p currNode = headNode->next;
    int size = 0;
    do
    {
        clearScreen();
        int total = getFlightCount(headNode);
        int totalPages = (total + pageSize - 1) / pageSize;
        printf("                                      全部航班信息(第%d页/共%d页)\n", currPage, totalPages);
        print_Lines5();
        printf("共有%d 个航班信息,信息如下:\n", total);
        print_Lines6();
        printf("序号:  航班公司     航班号\t起飞地->目的地\t    起飞时间\t       剩余票      状态\n");
        print_Lines6();
        int count = 0;
        int index = 1; // 序号

        flight_Node_p pageStart = currNode; // 保存当前页起始节点

        while (currNode != headNode && count < pageSize)
        {
            printf(" %2d    %s     %4s       %4s->%4s\t%s %s\t%3d      ",
                   index,
                   currNode->data->airline,
                   currNode->data->flight_id,
                   currNode->data->start,
                   currNode->data->end,
                   currNode->data->date,
                   currNode->data->time,
                   seatOrRemainder_num(currNode, 1));
            if (currNode->data->status == 1)
            {
                printf(COLOR_BLUE "%s\n" COLOR_RESET, get_status(currNode->data->status));
            }
            else
            {
                printf(COLOR_GREEN "%s\n" COLOR_RESET, get_status(currNode->data->status));
            }
            index++;
            print_Lines5();
            count++;
            currNode = currNode->next;
        }
        printf("指令: (序号)详细信息 (F)查询条件 (L)录入航班 (A)上一页 (D)下一页 (Q)退出: ");
        // 翻页
        while (1)
        {
            char input;
            scanf(" %c", &input);
            clearChar();
            int index = input - '0';
            if (total >= pageSize)
            {
                if (currPage * pageSize >= total)
                {
                    size = total - (currPage - 1) * pageSize; // 不足一页
                }
                else
                {
                    size = pageSize; // 中间页
                }
            }
            else
            {
                size = total;
            }
            if (index >= 1 && index <= size)
            {
                flight_Node_p findNode = pageStart;
                for (int i = 0; i < (index - 1) % pageSize; i++)
                    findNode = findNode->next;
                int status = show_DetailFlight(findNode);
                if (status == 2)
                {
                    currNode = headNode->next;
                    break;
                }
                currNode = pageStart;
                break;
            }

            else if (input == 'F' || input == 'f')
            {
                show_allFlight_temp(pageStart, pageSize, total, currPage);
                searchFlight_admin(headNode);
                currNode = pageStart;
                clearScreen();
                break;
            }

            else if (input == 'L' || input == 'l')
            {
                user_Node_p user = find_userNode(user_headNode, Login_Username);
                printf("是否开始录入?(Y/N):");
                if (if_goOn() == -1)
                {
                    currNode = pageStart;
                }
                else
                {
                    add_Flight(headNode, user->data->airline);
                    currNode = headNode->next;
                    currPage = 1;
                }
                break;
            }

            else if (input == 'a' || input == 'A')
            {
                if (currPage > 1)
                {
                    flight_Node_p newStart = pageStart;
                    for (int i = 0; i < pageSize && newStart->prev != headNode; i++)
                    {
                        newStart = newStart->prev;
                    }
                    if (newStart != pageStart)
                    { // 确认指针已移动
                        currNode = newStart;
                        currPage--;
                        clearScreen();
                        break;
                    }
                }
                else
                {
                    printf("已经是第一页了,请按D移到下一页:");
                }
            }

            else if (input == 'd' || input == 'D')
            {
                if (currPage < totalPages)
                {
                    if (currNode != headNode)
                    { // 确保没有越界
                        currPage++;
                        clearScreen();
                        break;
                    }
                }
                else
                {
                    printf("已经是最后一页了,请按A移到上一页:");
                }
            }
            else if (input == 'q' || input == 'Q')
            {
                return;
            }
            else
            {
                printf("输入错误,请重新输入:");
            }
        }
    } while (1);
}

// 显示航班信息(临时)
void show_allFlight_temp(flight_Node_p headNode, int pageSize, int total, int currPage)
{
    clearScreen();
    int totalPages = (total + pageSize - 1) / pageSize; // 计算总页数

    flight_Node_p currNode = headNode;

    printf("                          查询航班信息(第%d页/共%d页)\n", currPage, totalPages);
    print_Lines();
    printf("共有%d 个航班信息,信息如下:\n", total);
    print_Lines2();
    printf("序号:  航班公司     航班号\t起飞地->目的地\t    起飞时间\t       剩余票\n");
    print_Lines2();
    int count = 0;
    int index = 1;
    if (total < pageSize)
    {
        pageSize = total;
    }
    while (currNode != NULL && count < pageSize)
    {
        printf(" %2d    %s     %4s       %4s->%4s\t%s %s\t%3d\n",
               index,
               currNode->data->airline,
               currNode->data->flight_id,
               currNode->data->start,
               currNode->data->end,
               currNode->data->date,
               currNode->data->time,
               seatOrRemainder_num(currNode, 1));
        index++;
        print_Lines();
        count++;
        currNode = currNode->next;
    }
}

// 选择查询条件
void searchFlight_admin(flight_Node_p headNode)
{
    printf("[1] 航班号 [2] 起始地 [3] 目的地 [4] 日期 [5] 时间 [6] 价格 [Q] 返回\n");
    printf("请指定查询条件：");
    while (1)
    {
        char input;
        scanf(" %c", &input);
        clearChar();
        flight_Node_p resultNode = NULL;
        switch (input)
        {
        case '1':
            flight_Node_p currNode = find_flightByNo(headNode);
            if (currNode != NULL)
                show_DetailFlight(currNode);
            return;
        case '2':
            resultNode = find_flightByStart(headNode);
            if (resultNode == NULL)
            {
                return;
            }
            show_allFlight(resultNode);
            free_flightList(resultNode);
            return;
        case '3':
            resultNode = find_flightByEnd(headNode);
            if (resultNode == NULL)
            {
                return;
            }
            show_allFlight(resultNode);
            free_flightList(resultNode);
            return;
        case '4':
            resultNode = find_flightByDate(headNode);
            if (resultNode == NULL)
            {
                return;
            }
            show_allFlight(resultNode);
            free_flightList(resultNode);
            return;
        case '5':
            resultNode = find_flightByTime(headNode);
            if (resultNode == NULL)
            {
                return;
            }
            show_allFlight(resultNode);
            free_flightList(resultNode);
            return;
        case '6':
            resultNode = find_flightByPrice(headNode);
            if (resultNode == NULL)
            {
                return;
            }
            show_allFlight(resultNode);
            free_flightList(resultNode);
            return;
        case 'Q':
        case 'q':
            return;
        default:
            printf("输入错误，请重新输入：");
            break;
        }
    }
}

int show_DetailFlight(flight_Node_p currNode)
{
    while (1)
    {
        flight_p flight = currNode->data;
        clearScreen();
        printf("                                             航班详细信息\n");
        printf("-------------------------------------------------------------------------------------------------------------\n");
        printf("航班信息为:\t\t\t\t\t\t");
        printf("航班座位及票价信息:\n");
        printf("===================================\t\t\t");
        printf("===================================================\n");
        printf("航空公司:\t%s\t\t\t\t", flight->airline);
        printf("\t商务舱\t一等舱\t经济舱\t头等舱\t公务舱\n");

        printf("-----------------------------------\t\t\t");
        printf("===================================================\n");
        printf("航班号:\t\t%s\t\t\t\t\t", flight->flight_id);
        printf("票价:\t%d\t%d\t%d\t%d\t%d\n", flight->price[0], flight->price[1], flight->price[2], flight->price[3], flight->price[4]);
        printf("-----------------------------------\t\t\t");
        printf("---------------------------------------------------\n");
        printf("航线:\t\t%s->%s\t\t\t\t", flight->start, flight->end);
        printf("座位:\t%d\t%d\t%d\t%d\t%d\n", flight->seat[0], flight->seat[1], flight->seat[2], flight->seat[3], flight->seat[4]);
        printf("----------------------------------\t\t\t");
        printf("---------------------------------------------------\n");
        printf("起飞时间:\t%s %s\t\t\t", flight->date, flight->time);
        printf("余票:\t%d\t%d\t%d\t%d\t%d\n", flight->remainder[0], flight->remainder[1], flight->remainder[2], flight->remainder[3], flight->remainder[4]);
        printf("===================================\t\t\t");
        printf("===================================================\n");
        printf("-------------------------------------------------------------------------------------------------------------\n");
        printf("指令: (1) 更新航班 (2)取消航班 (3) 查看已预约用户 (Q)返回上一级:");
        char input;
        while (1)
        {
            scanf(" %c", &input);
            switch (input)
            {
            case '1':
                show_DetailFlight_temp(currNode);
                updata_Flight(currNode);
                break;
            case '2':
                int status = delete_Flight(currNode);
                if (status == 1)
                {
                    return 2;
                }
                else
                {
                    return -1;
                }
            case '3':
                find_bookedUsers(currNode->data->flight_id);
                break;
            case 'Q':
            case 'q':
                clearScreen();
                return 0;
            default:
                printf("输入错误,请重新输入!\n");
                break;
            }
            break;
        }
    }
}

int show_DetailFlight_temp(flight_Node_p currNode)
{
    flight_p flight = currNode->data;
    clearScreen();
    printf("                                             航班详细信息\n");
    printf("-------------------------------------------------------------------------------------------------------------\n");
    printf("航班信息为:\t\t\t\t\t\t");
    printf("航班座位及票价信息:\n");
    printf("===================================\t\t\t");
    printf("===================================================\n");
    printf("航空公司:\t%s\t\t\t\t", flight->airline);
    printf("\t商务舱\t一等舱\t经济舱\t头等舱\t公务舱\n");

    printf("-----------------------------------\t\t\t");
    printf("===================================================\n");
    printf("航班号:\t\t%s\t\t\t\t\t", flight->flight_id);
    printf("票价:\t%d\t%d\t%d\t%d\t%d\n", flight->price[0], flight->price[1], flight->price[2], flight->price[3], flight->price[4]);
    printf("-----------------------------------\t\t\t");
    printf("---------------------------------------------------\n");
    printf("航线:\t\t%s->%s\t\t\t\t", flight->start, flight->end);
    printf("座位:\t%d\t%d\t%d\t%d\t%d\n", flight->seat[0], flight->seat[1], flight->seat[2], flight->seat[3], flight->seat[4]);
    printf("----------------------------------\t\t\t");
    printf("---------------------------------------------------\n");
    printf("起飞时间:\t%s %s\t\t\t", flight->date, flight->time);
    printf("余票:\t%d\t%d\t%d\t%d\t%d\n", flight->remainder[0], flight->remainder[1], flight->remainder[2], flight->remainder[3], flight->remainder[4]);
    printf("===================================\t\t\t");
    printf("===================================================\n");
    printf("-------------------------------------------------------------------------------------------------------------\n");
    printf("请输入需要更新的航班信息: (1) 航班号 (2) 目的地 (3) 出发地 (4)日期 (5) 时间 (6) 票价 (7)座位数 (Q)返回:");
}

void updata_Flight(flight_Node_p currNode)
{
    char input;
    scanf(" %c", &input);
    clearChar();
    switch (input)
    {
    case '1':
        updata_flight_id(currNode);
        break;
    case '2':
        updata_start(currNode);
        break;
    case '3':
        updata_end(currNode);
        break;
    case '4':
        updata_date(currNode);
        break;
    case '5':
        updata_time(currNode);
        break;
    case '6':
        updata_price(currNode);
        break;
    case '7':
        updata_seat(currNode);
        break;
    case 'Q':
    case 'q':
        return;
    default:
        printf("输入错误,请重新输入!\n");
        break;
    }
    waitForAnyKey();
}

// 取消航班
int delete_Flight(flight_Node_p currNode)
{
    int seat = seatOrRemainder_num(currNode, 0);
    int remainder = seatOrRemainder_num(currNode, 1);
    if (seat - remainder > 0)
    {
        printf("本航班已有%d人预定,剩余%d个座位,确认删除?(Y/N):\n", seat - remainder, remainder);
    }
    else
    {
        printf("确认取消该航班?(Y/N)");
    }
    if (if_goOn() == -1)
    {
        printf("已取消删除!\n");
        return -1;
    }
    else
    {
        printf("请输入管理员密码:");
        user_Node_p user = find_userNode(user_headNode, Login_Username);
        char password[20];
        scanf("%s", password);
        clearChar();

        if (strcmp(user->data->password, password) != 0)
        {
            printf("密码错误,已取消删除!\n");
            return -1;
        }

        my_flight_deleteByFlight_id(myflight_headNode, currNode->data->flight_id);
        printf("正在归还顾客的金额...");
        cross_sleep(1000);
        printf("归还成功!\n正在删除航班信息...\n");
        flight_delete(currNode);
        flight_delete(find_flightByflight_id(flight_headNode, currNode->data->flight_id));
        cross_sleep(1000);
        printf("删除成功!\n");
        waitForAnyKey();
        return 1;
    }
}

void add_Flight(flight_Node_p headNode, char *airline)
{
    while (1)
    {
        flight_p flight = (flight_p)malloc(sizeof(flight_t));
    step1:
        while (1)
        {
            flight_scanf_steps1(flight, airline);

            printf("\n指令: (Y) 下一步 (N)上一步 (Q) 退出:");
            int status = if_goOn_add_Q();
            if (status == 1)
            {
                break;
            }
            else if (status == -1)
            {
                goto step1;
            }
            else if (status == 0)
            {
                return;
            }
        }
    step2:
        while (1)
        {
            flight_scanf_steps2(flight);

            printf("\n请选择后续操作:\n");
            printf("[1] 返回修改基本信息\n");
            printf("[2] 重新输入票价和座位信息\n");
            printf("[3] 确认保存航班信息\n");
            printf("请输入选项(1-3): ");
            int choice = 0;
            while (1)
            {
                scanf(" %d", &choice);
                clearChar();
                if (choice == 1)
                {
                    goto step1;
                }
                else if (choice == 2)
                {
                    goto step2;
                }
                else if (choice == 3)
                {
                    flight_insert(headNode, flight);
                    flight_insert(flight_headNode, flight);
                    printf("航班信息已保存。\n");
                    return;
                }
                else
                {
                    printf("无效选项，请重新输入。\n");
                }
            }
        }
    }
}

void flight_scanf_steps1(flight_p flight, char *airline)
{
    clearScreen();
    printf("                      录入航班信息(1/4)\n");
    print_Lines3();
    strcpy(flight->airline, airline);
    printf("请依次输入航班信息:\n");
    printf("航班号:\n");
    while (1)
    {
        scanf(" %6s", flight->flight_id);
        clearChar();
        int status = validate_string_format(flight->flight_id);
        if (status == 0)
        {
            printf("输入格式错误,航班号格式为前两位大写字母,后四位数字!\n请重新输入:");
            continue;
        }

        if (find_flight_id(flight_headNode, flight->flight_id) == 1)
        {
            printf("该航班号已存在!\n");
            continue;
        }
        break;
    }
    printf("起飞地 目的地:\n");
    scanf(" %19s %19s",

          flight->start,
          flight->end);
    clearChar();
    printf("起飞日期(YYYY-MM-DD):");

    while (1)
    {
        scanf(" %10s", flight->date);
        clearChar();
        if (!isValidDate(flight->date))
        {
            printf("日期格式错误!请按YYYY-MM-DD格式输入有效日期\n");
            continue;
        }
        break;
    }
    printf("起飞时间(HH:MM):");
    while (1)
    {
        scanf("%5s", flight->time);
        clearChar();
        if (!isValidTime(flight->time))
        {
            printf("时间格式错误!请按HH:MM格式输入有效时间\n");
            continue;
        }
        break;
    }
    printf("航班信息已保存。\n");
    clearScreen();
    printf("                      录入航班信息(2/4)\n");
    printf("---------------------------------------------------------------\n");
    printf("航班信息为:\n");
    printf("===================================\n");
    printf("航空公司:\t%s \n", flight->airline);
    printf("-----------------------------------\n");
    printf("航班号:\t\t%s \n", flight->flight_id);
    printf("-----------------------------------\n");
    printf("航线:\t\t%4s->%4s \n", flight->start, flight->end);
    printf("-----------------------------------\n");
    printf("起飞时间:\t%s %s\n", flight->date, flight->time);
    printf("===================================\n");
}

void flight_scanf_steps2(flight_p flight)
{
    clearScreen();
    printf("                      录入航班信息(3/4)\n");
    print_Lines3();

    printf("请轮流输入票价:\n");
    for (int i = 0; i < 5; i++)
    {
        printf("%s:", flight_index_to_type(i));
        scanf("%d", &flight->price[i]);
        clearChar();
    }
    printf("请轮流输入座位数:\n");
    for (int i = 0; i < 5; i++)
    {
        printf("%s:", flight_index_to_type(i));
        scanf("%d", &flight->seat[i]);
        clearChar();
        flight->remainder[i] = flight->seat[i];
    }
    flight->status = 0;
    clearScreen();
    printf("                                         航班信息确认(4/4)\n");
    printf("=============================================================================================================\n");
    printf("航班信息为:\t\t\t\t\t\t");
    printf("航班座位及票价信息:\n");
    printf("===================================\t\t\t");
    printf("===================================================\n");
    printf("航空公司:\t%s\t\t\t\t", flight->airline);
    printf("\t商务舱\t一等舱\t经济舱\t头等舱\t公务舱\n");

    printf("-----------------------------------\t\t\t");
    printf("===================================================\n");
    printf("航班号:\t\t%s\t\t\t\t\t", flight->flight_id);
    printf("票价:\t%d\t%d\t%d\t%d\t%d\n", flight->price[0], flight->price[1], flight->price[2], flight->price[3], flight->price[4]);
    printf("-----------------------------------\t\t\t");
    printf("---------------------------------------------------\n");
    printf("航线:\t\t%4s->%4s\t\t\t\t", flight->start, flight->end);
    printf("座位:\t%d\t%d\t%d\t%d\t%d\n", flight->seat[0], flight->seat[1], flight->seat[2], flight->seat[3], flight->seat[4]);
    printf("----------------------------------\t\t\t");
    printf("---------------------------------------------------\n");
    printf("起飞时间:\t%s %s\n", flight->date, flight->time);
    printf("===================================\t\t\n");
}

// 查看已经预约用户
void find_bookedUsers(char *flight_id)
{
    my_flight_Node_p headNode = get_bookedUsersFlightList(myflight_headNode, flight_id);

    const int pageSize = 10; // 每页显示10条记录
    int currPage = 1;
    my_flight_Node_p currNode = headNode->next;
    int size = 0;
    do
    {
        clearScreen();
        int total = getMyFlightCount(headNode);
        int totalPages = (total + pageSize - 1) / pageSize;
        printf("                                 %s--预约用户列表(第%d页/共%d页)\n", flight_id, currPage, totalPages);
        print_Lines5();
        printf("共有%d 个预约用户信息,信息如下:\n", total);
        print_Lines6();
        printf("用户名\t\t座位类型\t票价\t\t\t用户名\t\t座位类型\t票价\n");
        print_Lines6();
        int count = 0;

        my_flight_Node_p pageStart = currNode; // 保存当前页起始节点

        while (currNode != headNode && count < pageSize)
        {
            count++;
            printf("%s\t\t %s\t\t%d\t\t\t", currNode->data->username, flight_index_to_type(currNode->data->seat_type), currNode->data->price);
            if (currNode->next == headNode)
            {
                count++;
                printf("\n");
            }
            else
            {
                count++;
                currNode = currNode->next;
                printf("%s\t\t %s\t\t%d\n", currNode->data->username, flight_index_to_type(currNode->data->seat_type), currNode->data->price);
            }
            print_Lines5();

            currNode = currNode->next;
        }
        printf("指令: (A)上一页 (D)下一页 (Q)返回上一级: ");
        // 翻页
        while (1)
        {
            char input;
            scanf(" %c", &input);
            clearChar();
            if (input == 'a' || input == 'A')
            {
                if (currPage > 1)
                {
                    my_flight_Node_p newStart = pageStart;
                    for (int i = 0; i < pageSize && newStart->prev != headNode; i++)
                    {
                        newStart = newStart->prev;
                    }
                    if (newStart != pageStart)
                    { // 确认指针已移动
                        currNode = newStart;
                        currPage--;
                        clearScreen();
                        break;
                    }
                }
                else
                {
                    printf("已经是第一页了,请按D移到下一页:");
                }
            }

            else if (input == 'd' || input == 'D')
            {
                if (currPage < totalPages)
                {
                    if (currNode != headNode)
                    { // 确保没有越界
                        currPage++;
                        clearScreen();
                        break;
                    }
                }
                else
                {
                    printf("已经是最后一页了,请按A移到上一页:");
                }
            }
            else if (input == 'q' || input == 'Q')
            {
                return;
            }
            else
            {
                printf("输入错误,请重新输入:");
            }
        }
    } while (1);
    free_my_flightList(headNode);
}